<template>
  <div>
    <!-- 新增按钮 -->
    <a-button type="primary" @click="handleShowAddModal">新增学期</a-button>
<br>
    <!-- 显示当前学期 -->
      <!--        显示的labId-->
      <div style="margin:5px;align-content:center;font-size: 14px;background-color: #e6f7ff;padding:8px 15px;border-radius:4px;border:1px solid #91d5ff;height: 38px">
          <span>当前学期：</span>
          <span>{{ showSemesterName || ' ' }}</span>
      </div>


    <!-- 数据表格 -->
    <a-table
      :dataSource="data.tableDatas"
      :columns="data.tableColumns"
      :pagination="{ current: data.pageIndex, pageSize: data.pageSize, total: data.total }"
      @change="handleTableChange"
    >
      <!-- 选择框 -->
      <a-table-column title="选择" dataIndex="selected" key="selected" width="80">
        <template #customRender="{ text, record }">
          <a-checkbox
            v-model:checked="record.selected"
            @change="handleSelectChange(record)"
            style="width: 16px; height: 16px; border: 1px solid #ccc; border-radius: 2px;"
          >
            <template #checked>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="green" xmlns="http://www.w3.org/2000/svg">
                <path d="M9 16.2L4.8 12l-1.4 1.4 5.6 5.6L21.4 7l-1.4-1.4L9 16.2z" />
              </svg>
            </template>
          </a-checkbox>
        </template>
      </a-table-column>

      <!-- 操作列 -->
      <a-table-column title="操作1">
        <template slot-scope="record">
          <!-- 判断申请状态显示不同的操作列内容 -->
          <a-button
            type="primary"
            @click="showEditModal(record)">修改
          </a-button>
        </template>
      </a-table-column>
    </a-table>


    <!-- 新增申请模态框 -->
    <a-modal
      title="新增学期"
      v-model:open="addModalVisible"
      @ok="semesterAdd"
      @cancel="resetAddForm"
    >
      <a-form :model="addForm" ref="addFormRef" @finishFailed="handleFinishFailed">
        <a-form-item label="学期时间">
          <a-select v-model.number="addForm.startYear"
                    @change="updateStartYearAdd"
                    placeholder="请选择起始年份">
            <a-select-option v-for="year in availableYears" :key="year" :value="year">{{ year }}</a-select-option>
          </a-select>
          <span>至</span>
          <a-select v-model.number="addForm.endYear"
                    :placeholder="'请选择结束年份（大于' + (addForm.startYear || '起始年份') + '）'"
                    @change="updateEndYearAdd"
          >
            <a-select-option v-for="year in availableYears" :key="year" :value="year">{{ year }}</a-select-option>
          </a-select>

          <a-select v-model="addForm.term"
                    placeholder="请选择学期"
                    @change="updateTermAdd"
          >
            <a-select-option value="1">第一学期</a-select-option>
            <a-select-option value="2">第二学期</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 设置当前学期模态框 -->

    <!-- 修改学期模态框 -->
    <a-modal
      title="修改学期"
      v-model:open="editModalVisible"
      @ok="semesterEdit"
      @cancel="resetEditForm"
    >
      <a-form :model="editForm" ref="editFormRef" @finishFailed="handleFinishFailed">
        <a-form-item label="学期时间">
          <a-select v-model.number="editForm.startYear"
                    @change="updateStartYearEdit"
                    placeholder="请选择起始年份">
            <a-select-option v-for="year in availableYears" :key="year" :value="year">{{ year }}</a-select-option>
          </a-select>
          <span>至</span>
          <a-select v-model.number="editForm.endYear"
                    :placeholder="'请选择结束年份（大于' + (editForm.startYear || '起始年份') + '）'"
                    @change="updateEndYearEdit"
          >
            <a-select-option v-for="year in availableYears" :key="year" :value="year">{{ year }}</a-select-option>
          </a-select>

          <a-select v-model="editForm.term"
                    placeholder="请选择学期"
                    @change="updateTermEdit"
          >
            <a-select-option value="1">第一学期</a-select-option>
            <a-select-option value="2">第二学期</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message, TableProps } from 'ant-design-vue'
import {
    $semesterList,
    $semesterAdd,
    $semesterEdit,
    $editSemester,
    $deleteSemester, $getSemester,
} from '@/views/semester/add/semesterAdd.ts'
import moment from 'moment'
import { h } from 'vue'

const availableYears = Array.from({ length: 30 }, (_, index) => 2021 + index)

//数据显示
const data = reactive({
  tableDatas: [],
  tableColumns: [
    {
      title: '选择',
      dataIndex: 'selected',
      key: 'selected',
      width: 80
    },
    {
      title: '申请ID',
      dataIndex: 'id',
      key: 'id'
    },
    {
      title: '申请学期',
      dataIndex: 'semesterName',
      key: 'semesterName'
    }
  ],
  pageIndex: 1,
  pageSize: 10,
  total: 0,
  // 新增一个变量用来控制勾选框的状态
  isCurrentSemester: false
})
const addModalVisible = ref(false)
const addFormRef = ref(null)
const editFormRef = ref(null)
const editModalVisible = ref(false)
const showSemesterName = ref();
const setModelVisible = ref(false)
const nowSelectedRows = reactive([])
const isVisible = ref(true)
const currentSemester = ref(null)
import { Modal } from 'ant-design-vue'

// 新增中的各数据框
const addForm = reactive({
  startYear: null,
  endYear: null,
  term: null,
  semesterName: null
})

// 修改中的各数据框
const editForm = reactive({
  startYear: null,
  endYear: null,
  term: null,
  id: null,
  semesterName: null
})

// 更新表格列定义
data.tableColumns.push({
  title: '操作1',
  key: 'actionEdit',
  fixed: 'right',
  width: 100,
  customRender: ({ record }) => {
    return h('a', {
      style: { color: 'blue' },
      onClick: () => showEditModal(record)
    }, '修改')
  }
})
// 更新表格列定义
data.tableColumns.push({
  title: '操作2',
  key: 'actionChange',
  fixed: 'right',
  width: 150,
  customRender: ({ record }) => {
    return h('a', {
      style:{ color: 'blue' },
      onClick: () => setNowSemester(record)
    }, '设为当前学期')
  }
})
// 更新表格列定义
data.tableColumns.push({
  title: '操作3',
  key: 'actionDelete',
  fixed: 'right',
  width: 100,
  customRender: ({ record }) => {
    return h('a', {
      style: { color: 'red' },
      onClick: () => semesterDelete(record)
    }, '删除')
  }
})


//三个新增强制赋值
function updateStartYearAdd(value) {
  addForm.startYear = value
}

function updateEndYearAdd(value) {
  addForm.endYear = value
}

function updateTermAdd(value) {
  addForm.term = value
}

//三个修改强制赋值
function updateStartYearEdit(value) {
  editForm.startYear = value
}

function updateEndYearEdit(value) {
  editForm.endYear = value
}

function updateTermEdit(value) {
  editForm.term = value
}


//获取学期数据
async function fetchSemesterList() {
  try {
    const response = await $semesterList({}) // 调用后端接口获取学期列表
    const { data: semesterData } = response // 假设后端返回的数据字段名为 data
    data.tableDatas = semesterData.map(item => ({ id: item.id, semesterName: item.semesterName }))
    // 格式化后端返回的学期数据，并赋值给 tableDatas
  } catch (error) {
    console.error('Error fetching semester list:', error)
  }
}


// 处理提交新增
async function semesterAdd() {

  // 确保所有必要的字段都已填写
  if (!addForm.startYear || !addForm.endYear || !addForm.term) {
    message.error('请填写所有必填字段')
    return
  }

  // 确保第二个年份大于第一个年份，并且相差一年
  if (addForm.startYear >= addForm.endYear || addForm.startYear !== addForm.endYear - 1) {
    message.error('请选择正确的年份范围')
    return
  }

  // 生成semesterName
  const semesterName = `${addForm.startYear}-${addForm.endYear}-${addForm.term}`

  try {
    await $semesterAdd({ semesterName })
    message.success('学期添加成功')
    resetAddForm()
    fetchSemesterList()
    resetAddForm()
    addModalVisible.value = false
  } catch (error) {
    resetAddForm()
    message.error('添加学期时发生错误')
  }
}


async function semesterEdit() {
  // 确保所有必要的字段都已填写
  if (!editForm.startYear || !editForm.endYear || !editForm.term) {
    message.error('请填写所有必填字段')
    return
  }

  // 确保第二个年份大于第一个年份，并且相差一年
  if (editForm.startYear >= editForm.endYear || editForm.startYear !== editForm.endYear - 1) {
    message.error('请选择正确的年份范围')
    return
  }

  // 生成修改发送的semesterName
  editForm.semesterName = `${editForm.startYear}-${editForm.endYear}-${editForm.term}`

  try {
    // 构建params对象，包含id和semesterName字段
    const params = {
      id: editForm.id,
      semesterName: editForm.semesterName
    }

    // 调用$semesterEdit函数，并传递params对象作为参数
    await $semesterEdit(params)
    message.success('学期修改成功')
    resetEditForm()
    fetchSemesterList()
    resetEditForm()
    addModalVisible.value = false
  } catch (error) {
    resetEditForm()
    message.error('修改学期时发生错误')
  }
}


// 重置新增表单
function resetAddForm() {
  addForm.id = null
  addForm.semesterName = null
  addForm.startYear = null
  addForm.endYear = null
  addForm.term = null
  addFormRef.value.resetFields() // 使用 resetFields 方法重置表单字段的值

  /*  const addFormInputs = addFormRef.value.fields;
    for (const key in addFormInputs) {
      if (Object.hasOwnProperty.call(addFormInputs, key)) {
        addFormInputs[key].value = null;
      }
    }*/
  addModalVisible.value = false
}

function resetEditForm() {
  editForm.startYear = null
  editForm.endYear = null
  editForm.term = null
  editForm.id = null
  editForm.semesterName = null
  editFormRef.value.resetFields() // 使用 resetFields 方法重置表单字段的值

  /*  const editFormInputs = editFormRef.value.fields;
    for (const key in editFormInputs) {
      if (Object.hasOwnProperty.call(editFormInputs, key)) {
        editFormInputs[key].value = null;
      }
    }*/
  editModalVisible.value = false
}

//显示弹窗
function showEditModal(record) {
  /*
    editFromSend.id = record.id
  */
  editForm.id = record.id // 将记录的ID赋值给editForm对象的id字段

  editModalVisible.value = true
}

//触发弹窗显示
function handleShowAddModal() {
  addModalVisible.value = true
}

function handleSetAddModal() {
  if (data.isCurrentSemester) {
    // 弹出确认框
    Modal.confirm({
      title: '确认设置当前学期',
      content: '是否确定将选中的学期设置为当前学期？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        // 在这里执行设置当前学期的操作，可以根据实际需求发送请求给后端处理
        // ...

        // 清空勾选状态
        data.isCurrentSemester = false

        // 弹窗提示设置成功
        message.success('设置当前学期成功')
      }
    })
  } else {
    message.warning('请先选择学期')
  }
}

// 删除操作
async function semesterDelete(record) {
  const showMessage = (type, text) => {
    switch (type) {
      case 'success':
        message.success(text)
        break
      case 'error':
        message.error(text)
        return
      default:
        break
    }
  }

  try {
    Modal.confirm({
      title: '确认删除',
      content: '是否确认删除该申请？',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        let id = record.id
        console.log("id",id)
        let result = await $deleteSemester({id})
        console.log("result",result)
        const { code, message } = result
        console.log("code",code)
        if (code === 200) {
          showMessage('success', '删除成功')
          showSemesterName.value=null
          fetchSemesterList() // 更新数据
        } else {
          showMessage('error', '删除失败: ' + message)
        }
      }
    })
  } catch (error) {
    console.error('删除失败:', error)
  }
}


onMounted(async () => {

    //获取当前
    fetchSemesterList()
    try {
        let {code,message:resultMessage,data} = await $getSemester();
        if(code==200){
            const {id,semesterName}=data
            showSemesterName.value=semesterName
        }else{
            message.error(resultMessage)
        }
    }catch (e){
        message.error("获取失败")
    }


})

function handleTableChange(pagination, filters, sorter) {
  data.pageIndex = pagination.current
  data.pageSize = pagination.pageSize
  fetchSemesterList()
}

// 表单提交失败回调
function handleFinishFailed(errorInfo) {
  const errorFields = errorInfo.errorFields
  errorFields.forEach(field => {
    const fieldName = field.name[0]
    const errorMessage = field.errors[0]
    message.error(`"${fieldName}" ${errorMessage}`)
  })
}

/*
设置列的学期为当前学期
 */
const setNowSemester = async (record: any) => {
  console.log("nowRecord",record)
  let {id,semesterName} = record
  console.log("id",id)
  let result = await $editSemester({ id:id } )
  console.log("changeResult",result)
  let {code } =result
  if(code==200){
    showSemesterName.value = semesterName
    message.success("设置当前学期成功")
  }else{
    message.error("设置当前学期失败")
  }
 }

</script>


<style>
.ant-table-cell-fix-right .ant-btn-primary {
  background-color: #1890ff;
  border-color: #1890ff;
}


</style>
